import React, { memo, useEffect, useRef, useState } from 'react';
import { ScrollWrapper } from '@/base-ui/scroll-view/style'
import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'

const ScrollView = memo((props) => {
  // 内部状态
  const [showLeft, setShowLeft] = useState(false);
  const [showRight, setShowRight] = useState(false);
  const [posIndex, setPosIndex] = useState(0)
  const totalDistanceRef = useRef();
  //
  const scrollContentRef = useRef();

  useEffect(() => {
    const scrollWidth = scrollContentRef.current.scrollWidth; // 一共可以滚动的宽度
    const clientWidth = scrollContentRef.current.clientWidth; // 本身宽度
    const totalDistance = scrollWidth - clientWidth;
    totalDistanceRef.current = totalDistance; // 记录当前滚动距离
    setShowRight(totalDistance > 0);
  }, [props.children]);

  function controlClickHandle(flag){
    const newIndex = flag ? posIndex + 1 : posIndex - 1;
    const newEl = scrollContentRef.current.children[newIndex]
    const newOffsetLeft = newEl.offsetLeft;
    scrollContentRef.current.style.transform = `translate(-${newOffsetLeft}px)`;
    setPosIndex(newIndex);
    setShowRight(totalDistanceRef.current > newOffsetLeft);
    setShowLeft(newOffsetLeft>0);
  }

  return (
    <ScrollWrapper>
      {
        showLeft && <div className='control left' onClick={ () => controlClickHandle(false) }>
          <IconArrowLeft></IconArrowLeft>
        </div>
      }
      {
        showRight && <div className="control right"  onClick={ () => controlClickHandle(true) }>
          <IconArrowRight></IconArrowRight>
        </div>
      }

      <div className="scroll">
        <div className="scroll-content" ref={ scrollContentRef }>
          { props.children }
        </div>
      </div>
    </ScrollWrapper>
  );
});

export default ScrollView;
